package com.blog.Bard.common.interceptor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.blog.Bard.base.pojo.UrlMatching;
import com.blog.Bard.base.service.UrlMatchingService;
import com.blog.Bard.common.util.JwtUtil;

/**
 * 拦截器
 *
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UrlMatchingService urlMatchingService;
	
	private static final Integer lock = 0;
	
	private static Map<String, String> urls = null;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.info("exec CheckTokenInterceptor's preHandle method...");
//		Map<String, String[]> parameterMap = request.getParameterMap();
//		Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
//		Iterator<Entry<String, String[]>> iterator = entrySet.iterator();
		
		boolean matching = matchingNotCheckUrl(request, response, handler);
		
		if(!matching) {
			Cookie[] cookies = request.getCookies();
			if(cookies==null) {
				response.sendRedirect("/");
			}else {
				int i=0;
				for(Cookie c : cookies) {
					String name = c.getName();
					String value = c.getValue();
					if("ETtoken".equals(name)) {
						try {
							JwtUtil.verifyToken(value);
							return true;
						}catch (Exception e) {
							e.printStackTrace();
							response.sendRedirect("/");
						}
					}
				}
				if(i==0) {
					response.sendRedirect("/");
				}
			}
		}
		
		
//		while (iterator.hasNext()) {
//			Entry<String, String[]> next = iterator.next();
//			System.out.println(next.getKey() + ":" + Arrays.toString(next.getValue()));
//		}
		return true;
	}
	
	/**
	 * 匹配是否不验证的请求路径
	 * @param request
	 * @param response
	 * @param handler
	 * @throws Exception 
	 */
	public boolean matchingNotCheckUrl(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String requestURI = request.getRequestURI();
		System.out.println("当前访问的是:" + requestURI);
		
		if(urls==null) {
			synchronized (lock) {
				createUrlMatching();
			}
		}
		
		String matching = urls.get(requestURI);
		if(matching!=null) {
			return true;
		}
		
		return false;
	}
	
	/**
	 * 创建匹配非验证路径对象
	 * @throws Exception
	 */
	private void createUrlMatching() throws Exception{
		if(urls==null) {
			urls = new HashMap<String, String>();
			List<UrlMatching> list = urlMatchingService.findAll();
			for(int i=0;i<list.size();i++) {
				UrlMatching matching = list.get(i);
				urls.put(matching.getUrl(), matching.getUrlCode());
			}
		}
	}
	
}
